const mysql = require('mysql');

let conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: "rain_news",
    port: '3306',
	// connectTimeout: 1000 * 60 * 60
})

function query(sql, callback, param){
	// 重新连接
	conn = mysql.createConnection(conn.config);
	conn.connect();
	const arr = [sql, (err, data) => {
		// console.log(data);
		if(err){
			// 报错
		}else{
			callback(data);
		}
	}];
	if(param){
		arr.splice(1, 0, param);
	}
	conn.query(...arr);
	// 断开连接
	conn.end();
}

// 查询整个表内容
function search(table = 'user'){
	let sql = `select distinct * from ${table} order by id`;
	console.log(sql)
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data)
		});
	})
}

// 根据条件查询
function searchBy(sql){
	// let sql = `select distinct * from ${table} ${condition}`;
	console.log(sql)
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data)
		});
	})
}


// 添加
function add(param, condition){
	let sql = `insert into ${condition}`;
	console.log(sql)
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data)
		}, param);
	})
}

// 修改
function edit(condition){
	let sql = `UPDATE ${condition}`;
	console.log(sql)
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data)
		});
	})
}

// 删除
function del(condition){
	let sql = `delete from ${condition}`;
	console.log(sql)
	return new Promise(resolve => {
		query(sql, data => {
			resolve(data)
		});
	})
}


module.exports = {
	search,
	searchBy,
	add,
	del,
	edit
}